home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Nee help with a string and temp string
- Date: Sat, 13 Apr 96 16:05:39 GMT
- Organization: none
- Message-ID: <829411539snz@genesis.demon.co.uk>
- References: <316C72CC.763A@cloudnet.com> <316DB246.74FB@willows.com>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <316DB246.74FB@willows.com>
- tarang@willows.com "Tarang Deshpande" writes:
-
- >Randall J. Pfeifer wrote:
- >>
- >> I am writing a program that reads data, validates it, and then writes it to a
- > new file.
- >> ...
- >>
- >> My problem involves lines 2 through X.
- >> Reading the data is fine. However, when I evaluate the components and write
- > them to the
- >> buffer the previous lines data still resides in the string.
-
- >> void examineBcard()
- >> { int result;
- >>
- >> strncpy(Bcard,"B",1);
- >> strncat(Bcard,&line[1],1);
- >> strncat(Bcard, Space,3);
- >>
- >> padright(Bcard,5,7,3,3);
- >> padright(Bcard,8,12,5,5);
- >> padright(Bcard,13,18,6,6);
- >> strncat(Bcard," ",1);...
- >
- >Note that in C the end of a string is marked by a null character or
- >char(0).
-
- Hold that thought.
-
- Your call to strncpy is equivilant to the following:
-
- >Bcard [ 0 ] = 'B';
- >Bcard [ 1 ] = '\0';
-
- Wrong. strncpy() always writes exactly the number of characters you specify
- to the target buffer. It does not guarantee that the result is a string i.e.
- null character terminated and is an oddity in the standard string library.
- In this case it simply corresponds to:
-
- Bcard[0] = 'B';
-
- So the subsequent call to strncat which depends on its first argument
- pointing to a null character terminated string isn't going to work properly.
- You could fix this by changing strncpy() to simply strcpy() with the
- first 2 arguments or you could simplify that group of three lines to:
-
- sprintf(Bcard, "B%c ", line[1]);
-
- or character-wise:
-
- Bcard[0] = 'B';
- Bcard[1] = line[1];
- Bcard[2] = ' ';
- Bcard[3] = ' ';
- Bcard[4] = ' ';
- Bcard[5] = '\0';
-
- sprintf is far more flexible though, it can probably replace the calls to
- padright as well and the resulting code will be much clearer. I've no idea
- what the arguments to padright() specify (I can probably guess the first!)
-
- >The call in no way affects Bcard [ x ] where x >= 2. I suspect that
- >the problem is in you padright function which does not put a trailing
- >null character at the end. This is one solution.
-
- It doesn't fix the immediate problem.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-